<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :check-strictly="true"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="sheetsCode"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              v-loading="treeLoading"
              show-checkbox
              @check="getList"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span>{{ node.label }}</span>
                  <!--                  <span v-if="data.deviceCount!=null" class="device-count">{{data.deviceCount}}</span>-->
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;height: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch"
                       :label-width="labelWidth">
                <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                  <el-form-item label="集中器名称" prop="concentratorName">
                    <el-input size="mini"
                              v-model="queryParams.concentratorName"
                              placeholder="请输入集中器名称"
                              clearable
                              @keyup.enter="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="集中器地址" prop="concentratorId">
                    <el-input size="mini"
                              v-model="queryParams.concentratorId"
                              placeholder="请输入集中器地址"
                              clearable
                              @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="设备编号" prop="terminalId">
                    <el-input size="mini"
                              v-model="queryParams.terminalId"
                              placeholder="请输入设备编号"
                              clearable
                              @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="通讯类型" prop="communicationType">
                    <el-select clearable filterable v-model="queryParams.communicationType" placeholder="请选择通讯类型" style="width: 100%;">
                      <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属客户" prop="tenantId">
                    <el-select filterable v-model="queryParams.tenantId" clearable placeholder="请选择所属客户"
                               style="width: 100%;">
                      <el-option
                        v-for="dept in deptOption"
                        :key="dept.tenantId"
                        :label="dept.deptName"
                        :value="dept.tenantId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>

            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
              </el-button>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['basedata:concentrator:add']"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-has-permi="['basedata:concentrator:import']"
              >导入
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                size="mini"
                @click="selectMetered('绑定户表')"
              >绑定户表
              </el-button>
            </el-col>

            <RightDropdown :columns="columns" :showSearch.sync="showSearch" :uploadVisible="uploadVisible"
                           @queryTable="getList" @export="handleExport" @upload="handleUpload"
                           :hasPermiExport="['basedata:concentrator:export']" :hasPermiUpload="['basedata:concentrator:exportTemplate']"></RightDropdown>
          </el-row>

          <div style="height: 89%; margin-top: 5px;">
            <el-empty description="暂无集中器" v-if="concentratorList.length == 0"></el-empty>
            <el-row v-else style="height: 100%;">
              <el-col :span="4" style="height: 100%;">
                <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
                  <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                            style="width: 100%;margin-bottom: 10px;" v-model="filterConcentrator"/>
                  <el-tree ref="concentratorTree" :data="concentratorList"
                           :props="{children: 'children', label: 'concentratorName'}"
                           :filter-node-method="filterConcentratorNode" @node-click="handleNodeClick"
                           style="height: 95%;overflow-y: auto;"></el-tree>
                </div>
              </el-col>

              <el-col :span="20" style="border-left: 1px solid #e8e8e8;padding: 0 10px;">
                <div class="content-wrapper">
                  <el-descriptions class="margin-top" title="集中器基本信息" :column="5" :size="size" border>
                    <template slot="extra">
                      <el-button type="primary" icon="el-icon-edit" :size="size"
                                 @click="handleUpdate(selectedConcentrator)" v-has-permi="['basedata:concentrator:edit']">
                      </el-button>
                      <el-button type="danger" icon="el-icon-delete" :size="size"
                                 @click="handleDelete(selectedConcentrator)" v-has-permi="['basedata:concentrator:remove']">
                      </el-button>
                    </template>
                    <el-descriptions-item>
                      <template slot="label">
                        集中器名称
                      </template>
                      {{ selectedConcentrator.concentratorName }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        集中器ID
                      </template>
                      {{ selectedConcentrator.id }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        集中器地址
                      </template>
                      {{ selectedConcentrator.concentratorId }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        抄表日期
                      </template>
                      {{ selectedConcentrator.readDate }}
                    </el-descriptions-item>
                    <!--                    <el-descriptions-item>-->
                    <!--                      <template slot="label">-->
                    <!--                        通讯类型-->
                    <!--                      </template>-->
                    <!--                      {{ selectedConcentrator.communicationType }}-->
                    <!--                    </el-descriptions-item>-->
                  </el-descriptions>
                </div>
                <div class="content-wrapper">
                  <el-tabs v-model="activeName">
                    <el-tab-pane label="远程控制" name="1">
                      <el-row class="line-bottom">
                        <el-form :model="queryCommParams" ref="queryLogForm" :size="size" :label-width="labelWidth">
                          <div>

                            <el-form-item label="命令类型" prop="commandType">
                              <!-- <el-radio-group v-model="queryCommParams.commandType" size="mini" @change="change">
                                    <el-radio-button v-for="(item, index) in dict.type.concentrator_command_type"
                                                 :key="index" :label="item.label" :value="item.value">
                                </el-radio-button>
                              </el-radio-group> -->
                              <!-- <el-dropdown split-button type="primary" placement="top" @command="getCommand">
                                {{ commandName }}
                                  <el-dropdown-menu>
                                    <el-dropdown-item style="min-width: 300px;" v-for="(item, index) in dict.type.concentrator_command_type"
                                                 :key="index" :label="item.label" :value="item.value" :command="item.label">{{ item.label }}</el-dropdown-item>
                                  </el-dropdown-menu>
                              </el-dropdown> -->
                              <el-select v-model="queryCommParams.commandType" placeholder="请选择命令"
                                         style="width: 210px" @change="change">
                                <el-option
                                  v-for="item in dict.type.concentrator_command_type"
                                  :key="item.label"
                                  :label="item.label"
                                  :value="item.label"
                                />
                              </el-select>
                              <el-button type="primary" style="margin: 0px 0px 0px 10px" @click="openContorller">确认
                              </el-button>
                            </el-form-item>
                          </div>
                        </el-form>
                      </el-row>
                      <el-row style="min-height: 450px; margin: 20px;">
                        <el-descriptions class="margin-top" title="发送结果" :column="10">
                          <el-descriptions-item label="内容">{{ feedbackContent }}</el-descriptions-item>
                        </el-descriptions>
                        <el-descriptions class="margin-top" title="" :column="1" v-show="queryResult">
                          <el-descriptions-item label="查询结果">{{ information }}</el-descriptions-item>
                        </el-descriptions>
                      </el-row>
                    </el-tab-pane>
                    <el-tab-pane label="命令日志" name="2">
                      <!-- 记录查询 -->
                      <el-row class="line-bottom">
                        <el-col class="form_col">
                          <el-form :model="logQueryParams" ref="logQueryForm" size="mini"
                                   :label-width="labelWidth">
                            <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                              <el-form-item label="命令类型" prop="commandType">
                                <el-select v-model="logQueryParams.commandType"
                                           size="mini" style="width: 120%;"
                                           @keyup.enter.native="handleLogQuery"
                                           clearable placeholder="请选择命令类型">
                                  <el-option label="全部" value=""></el-option>
                                  <el-option v-for="(item, index) in dict.type.concentrator_command_type"
                                             :key="index" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                              </el-form-item>
                              <el-form-item label="时间" prop="sendTimeValue">
                                <el-date-picker size="mini"
                                                clearable
                                                v-model="sendTimeValue"
                                                type="daterange"
                                                range-separator="至"
                                                start-placeholder="开始日期"
                                                end-placeholder="结束日期"
                                                value-format="yyyy-MM-dd"
                                                style="width: 202px;">
                                </el-date-picker>
                              </el-form-item>
                              <el-form-item>
                              </el-form-item>
                            </div>
                          </el-form>
                        </el-col>
                        <el-col class="form_query">
                          <el-button type="primary" @click="handleLogQuery" size="mini">查询</el-button>
                          <el-button @click="resetLogQuery" size="mini">重置</el-button>
                        </el-col>
                      </el-row>

                      <el-table v-loading="loading" :data="logDataList" height="437" size="mini"
                                :height="getAvailableTableHeight - 45" border ref="table">
                        <el-table-column label="命令类型" align="center" prop="commandType"
                                         :show-overflow-tooltip="true">
                          <template slot-scope="scope">
                            <dict-tag :options="dict.type.concentrator_command_type"
                                      :value="scope.row.commandType"/>
                          </template>
                        </el-table-column>
                        <el-table-column label="集中器地址" align="center" prop="concentratorId"
                                         :show-overflow-tooltip="true"/>
                        <el-table-column label="绑定户表" align="center" prop="terminalIds"
                                         :show-overflow-tooltip="true"/>
                        <el-table-column label="发送结果" align="center" prop="feedback"
                                         :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="发送时间" align="center" prop="sendTime"
                                         :show-overflow-tooltip="true">
                          <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d}') }}</span>
                          </template>
                        </el-table-column>
                      </el-table>
                      <pagination
                        :total="logtotal"
                        :page.sync="logQueryParams.pageNum"
                        :limit.sync="logQueryParams.pageSize"
                        @pagination="getLogList"
                      />
                    </el-tab-pane>
                    <el-tab-pane label="绑定水表" name="3">
                      <div class="XbList">
                        <el-table v-loading="loading" :data="terminalxbList" @change="getXbList" border size="mini"
                                  :height="getAvailableTableHeight"
                                  ref="table">
                          <el-table-column type="index" width="40" label="#" align="center"/>
                          <el-table-column label="编号" align="center" prop="id" v-if="false"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="用户名称" align="center" prop="userName"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="用户编号" align="center" prop="userId"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="安装地址" align="center" prop="installAddress"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="设备编号" align="center" prop="terminalId"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="厂家名称" align="center" prop="supplierId"
                                           :show-overflow-tooltip="true" width="100">
                            <template slot-scope="scope">
                              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.supplierId"/>
                            </template>
                          </el-table-column>
                          <el-table-column label="表型号" align="center" prop="typeId"
                                           :show-overflow-tooltip="true" width="120">
                            <template slot-scope="scope">
                              <dict-tag :options="dict.type.module_type" :value="scope.row.typeId"/>
                            </template>
                          </el-table-column>
                          <el-table-column label="协议名称" align="center" prop="protocolName"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="通讯地址" align="center" prop="communicateAddress"
                                           :show-overflow-tooltip="true"/>
                          <el-table-column label="集中器" align="center" prop="concentratorName"
                                           :show-overflow-tooltip="true"/>
                        </el-table>
                      </div>
                      <pagination
                        :total="total"
                        :page.sync="queryXbParams.pageNum"
                        :limit.sync="queryXbParams.pageSize"
                        @pagination="getXbList"
                      />
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改集中器管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" :inline="true">
        <el-form-item label="区域名称" prop="sheetsCode">
          <!-- <el-input v-model="form.sheetsCode" placeholder="请输入区域名称" /> -->
          <treeselect v-model="form.sheetsCode"
                      :options="sheetsTreeList"
                      :normalizer="normalizer"
                      :show-count="true"
                      placeholder="请选择区域名称"
                      style="width:200px;">
            <template v-slot:option-label="{ node, shouldShowCount, count }">
              <span>
                <!-- 这里添加你的图标，可以是字体图标或图片 -->
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="node.raw.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="node.raw.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding"
                      v-if="node.raw.deviceType === 2"></span>
                {{ node.label }}
                <!-- 如果需要，可以显示选中的数量 -->
                <span v-if="shouldShowCount">({{ count }})</span>
              </span>
            </template>
          </treeselect>
        </el-form-item>
        <el-form-item label="集中器名称" prop="concentratorName">
          <el-input v-model="form.concentratorName" placeholder="请输入集中器名称"/>
        </el-form-item>
        <el-form-item label="集中器地址" prop="concentratorId">
          <el-input v-model="form.concentratorId" placeholder="请输入集中器地址"/>
        </el-form-item>
        <el-form-item label="集中器版本" prop="concentratorVer">
          <el-input v-model="form.concentratorVer" placeholder="请输入集中器版本"/>
        </el-form-item>
        <el-form-item label="集中器型号" prop="concentratorType">
          <el-input v-model="form.concentratorType" placeholder="请输入集中器型号"/>
        </el-form-item>
        <el-form-item label="厂家名称" prop="supplierId">
          <!--          <el-input v-model="form.supplierId" placeholder="请输入集中器型号" />-->
          <el-select v-model="form.supplierId" filterable placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="协议类型" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议类型" style="width: 202px" clearable>
            <el-option v-for="(item, index) of protocolOptionList" :key="index" :label="item.protocolName"
                       :value="item.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抄表日期" prop="readDate">
          <el-input v-model.number="form.readDate" placeholder="请输入抄表日期"/>
          <!-- <el-date-picker clearable
            v-model.number="form.readDate"
            type="datetime"
            placeholder="请选择抄表日期"
            style="width: 202px;"
            value-format="timestamp">
          </el-date-picker> -->
        </el-form-item>
        <!-- <el-date-picker clearable
          v-model="form.timeOver"
          type="datetime"
          placeholder="请选择超时时间"
          style="width: 202px;">
        </el-date-picker> -->
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址"/>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口"/>
        </el-form-item>
        <!-- <el-form-item label="网络接入点" prop="netPoint">
          <el-input v-model="form.netPoint" placeholder="请输入网络接入点" />
        </el-form-item> -->
        <el-form-item label="心跳周期" prop="heartbeatCycle">
          <el-input v-model.number="form.heartbeatCycle" placeholder="请输入心跳周期"/>
        </el-form-item>
        <el-form-item label="SIM卡号码" prop="simNum">
          <el-input v-model="form.simNum" placeholder="请输入SIM卡号码"/>
        </el-form-item>
        <!-- <el-form-item label="ccid" prop="ccid">
          <el-input v-model="form.ccid" placeholder="请输入CCID" />
        </el-form-item> -->
        <el-row>
          <el-form-item label="终端位置纬度" prop="lat">
            <el-input v-model="form.lat" placeholder="请输入纬度"/>
          </el-form-item>
          <el-form-item label="终端位置经度" prop="lng">
            <el-input v-model="form.lng" placeholder="请输入经度"/>
          </el-form-item>
          <!--          <el-form-item>
                      <i class="el-icon-location-information" style="color: #1890ff" @click="handleMap"></i>
                    </el-form-item>-->
        </el-row>
        <el-form-item label="通讯类型" prop="communicationType">
          <el-select v-model="form.communicationType" placeholder="请选择通讯类型" style="width: 202px;">
            <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属客户" prop="tenantId">
          <el-select filterable v-model="form.tenantId" placeholder="请选择所属客户" style="width: 202px;">
            <el-option
              v-for="dept in deptOption"
              :key="dept.tenantId"
              :label="dept.deptName"
              :value="dept.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="installAddress">
          <el-input v-model="form.installAddress" placeholder="请输入安装位置"/>
        </el-form-item>
        <!-- <el-form-item label="终端位置经纬度" prop="lngLatTemp">
          <el-input v-model="form.lngLatTemp" placeholder="请输入终端位置经纬度" />
        </el-form-item> -->
        <!-- 超时时间需要注释 -->
        <!-- <el-form-item label="超时时间" prop="timeOver">
          <el-input v-model="form.timeOver" placeholder="请输入超时时间" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 下发命令对话框 -->
    <el-dialog :title="controllerTitle" :visible.sync="ControllerOpen" width="850px" append-to-body>
      <el-form ref="controllerform" :model="controllerForm" :rules="controllerformrules" :label-width="labelWidth" :inline="true">
        <el-form-item label="命令类型" prop="commandType">
          <el-select v-model="controllerForm.commandType" :disabled="true" placeholder="请选择命令类型" style="width: 202px;">
            <el-option v-for="(item, index) in dict.type.concentrator_command_type" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="集中器地址" prop="concentratorId">
          <el-input v-model="controllerForm.concentratorId" :disabled="true" placeholder="请输入集中器地址"/>
        </el-form-item>
        <el-form-item label="集中器厂家" prop="supplierId">
          <el-select v-model="controllerForm.supplierId" placeholder="请选择集中器厂家" style="width: 202px;">
            <el-option v-for="(item, index) in dict.type.terminal_supplier" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <!-- <el-input v-model="form.supplierId" :disabled="true" placeholder="请输入集中器厂家" /> -->
        </el-form-item>
        <el-form-item label="上报时间" prop="sendTime" :rules="[{ required: controllerForm.supplierId === '1020', message: '请选择上报时间', trigger: 'change' }]" message="请选择上报时间"
                      v-if="controllerTitle === '下发命令名称-设置自动抄表上报时间及周期' || controllerTitle === '下发命令名称-日冻结数据'">
          <el-date-picker clearable
                          v-model="controllerForm.sendTime"
                          type="datetime"
                          value-format="yyyyMMddHHmm"
                          placeholder="请选择日期"
                          style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上报周期" prop="frequency"
                      v-if="controllerTitle == '下发命令名称-设置自动抄表上报时间及周期'" :rules="[{ required: controllerForm.supplierId === '1020', message: '请选择上报时间', trigger: 'change' }]">
          <!--          <el-select v-model="form.frequency" placeholder="请选择上报周期" style="width: 202px;">-->
          <!--            <el-option v-for="(item, index) in dict.type.frequency_meter_read" :key="index" :label="item.label"-->
          <!--                       :value="item.value"></el-option>-->
          <!--          </el-select>-->
          <el-input-number v-model="controllerForm.frequency" :min="1" label="上报周期" style="width: 101px"></el-input-number>
          <el-dropdown size="medium" split-button type="primary" @command="handleUnitCommand" style="width: 101px">
            {{ controllerForm.frequencyUnit === 'HOURS' ? '时' : (controllerForm.frequencyUnit === 'DAYS' ? '日' : '月') }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="HOURS">时</el-dropdown-item>
              <el-dropdown-item command="DAYS">日</el-dropdown-item>
              <el-dropdown-item command="MONTHS">月</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <!-- <el-form-item label="通讯地址" prop="meter"  v-show="this.title == '下发命令名称-单表数据抄取' || this.title == '下发命令名称-阀控'">
          <el-input v-model="form.meter" placeholder="请输入通讯地址" />
        </el-form-item> -->
        <!-- <el-form-item label="通讯地址" prop="meter"  v-show="this.title == '下发命令名称-配置绑定多个水表地址'">
          <el-input v-model="form.meters" placeholder="请输入通讯地址" />
        </el-form-item> -->
        <el-form-item label="IP" prop="ip" v-show="controllerTitle === '下发命令名称-设置 IP 及端口'">
          <el-input v-model="controllerForm.ip" placeholder="请输入IP地址"/>
        </el-form-item>
        <el-form-item label="端口" prop="port" v-show="controllerTitle === '下发命令名称-设置 IP 及端口'">
          <el-input v-model="controllerForm.port" placeholder="请输入端口号"/>
        </el-form-item>
        <!--        集中器 户表档案 实时数据开关阀-->
        <!--        2024.12.27 修改阀控 原始的是1开 2关 改后是0开1关-->
        <!--        下发是0开1关  从后端接收到的数据是0关1开-->
        <el-form-item label="阀控" prop="isOpen" v-show="controllerTitle === '下发命令名称-阀控'">
          <el-radio-group v-model="controllerForm.isOpen">
            <el-radio label="1">开</el-radio>
            <el-radio label="2">关</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态" prop="enable" v-show="controllerTitle === '下发命令名称-集中器自动上报启停'">
          <el-radio-group v-model="controllerForm.enable">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="厂家名称" prop="supplierId">
          <el-select v-model="form.supplierId" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="采集器" prop="collector"
                      v-show="controllerTitle === '下发命令名称-下载表档案' || controllerTitle === '下发命令名称-批量下载表档案'">
          <el-select v-model="controllerForm.collector" placeholder="请选择采集器" style="width: 202px;">
            <el-option v-for="(item, index) in collectorList" :key="index" :label="item.collectorName"
                       :value="item.collectorAdd"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="新集中器地址 " prop="newConcentratorId"
                      v-show="controllerTitle === '下发命令名称-设置集中器地址'">
          <el-input v-model="controllerForm.newConcentratorId" placeholder="请输入新的集中器地址"/>
        </el-form-item>

        <el-alert
          :closable="false"
          v-show="selectMeteredMessage.length != 0"
          :title="selectMeteredMessage"
          type="success">
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ControllerCancel">取 消</el-button>
        <el-button type="success" @click="selectMetered('户表选择')"
                   v-show="controllerTitle === '下发命令名称-配置绑定多个水表地址' || controllerTitle === '下发命令名称-单表数据抄取' || controllerTitle === '下发命令名称-阀控' || controllerTitle === '下发命令名称-下载表档案' || controllerTitle === '下发命令名称-实时数据' || controllerTitle === '下发命令名称-日冻结数据'|| controllerTitle === '下发命令名称-多表数据抄取' || controllerTitle === '下发命令名称-下载多表档案（QBT专用）'">
          户表选择
        </el-button>
        <el-button v-show="controllerTitle === '下发命令名称-下载多表档案（QBT专用）'" type="warning" @click="loadAllReport">下载全部档案</el-button>
        <el-button type="primary" @click="submitControllerForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 户表查询页面 -->
    <el-dialog :title="userModalTitle" :visible.sync="meteredOpen" width="1250px" append-to-body>
      <el-row>
        <el-form :model="meteredQueryParams" ref="mQueryForm" size="mini" :inline="true" label-width="70px">
          <el-form-item label="用户编号" prop="userId">
            <el-input
              v-model="meteredQueryParams.userId"
              placeholder="请输入用户编号"
              clearable
              @keyup.enter.native="handleMeteredQuery"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="设备编号" prop="terminalId">
            <el-input
              v-model="meteredQueryParams.terminalId"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handleMeteredQuery"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="IMEI" prop="imei">
            <el-input
              v-model="meteredQueryParams.imei"
              placeholder="请输入IMEI"
              clearable
              @keyup.enter.native="handleMeteredQuery"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="通讯地址" prop="communicateAddress">
            <el-input
              v-model="meteredQueryParams.communicateAddress"
              placeholder="请输入通讯地址"
              clearable
              @keyup.enter.native="handleMeteredQuery"
              class="input_w"
            />
          </el-form-item>
          <el-form-item label="通讯类型" prop="communicationType">
            <el-select filterable class="input_w" v-model="meteredQueryParams.communicationType" placeholder="请选择通讯类型">
              <el-option v-for="dict in dict.type.communication_type" :key="dict.value" :label="dict.label"
                         :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="绑定状态" prop="haveConcentrator" v-show="userModalTitle === '绑定户表'">
            <el-select class="input_w" v-model="meteredQueryParams.haveConcentrator" placeholder="请选择绑定状态">
              <el-option label="未绑定集中器" :value="false"></el-option>
              <el-option label="已绑定集中器" :value="true"></el-option>
              <el-option label="全部集中器" value=""></el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item v-show="userModalTitle=== '绑定户表'" label="绑定状态" prop="">-->
          <!--            <el-select v-model="meteredQueryParams." placeholder="请选择绑定状态">-->
          <!--              <el-option-->
          <!--                v-for="dict in dict.type.bind_status"-->‘
          <!--                :key="dict.value"-->
          <!--                :label="dict.label"-->
          <!--                :value="dict.value"-->
          <!--              ></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          如果是绑定户表 需要查询和集中器区域、协议相同的户表-->
          <!--          <el-form-item label="协议类型" prop="protocolId">-->
          <!--            <el-select v-model="meteredQueryParams.protocolId" placeholder="请选择协议类型" class="input_w" clearable>-->
          <!--              <el-option v-for="(item, index) of protocolOptionList" :key="index" :label="item.protocolName"-->
          <!--                         :value="item.protocolId"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" @click="handleMeteredQuery" size="mini">查询</el-button>
            <el-button @click="resetMeteredQuery" size="mini">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-table v-loading="meteredloading" :data="meteredDataList" row-key="id" border
                  @selection-change="handleSelectionChange" max-height="600" height="600" ref="meteredtable">
          <el-table-column type="selection" width="55" align="center" fixed :selectable="selectable"
                           :reserve-selection="true"/>
          <el-table-column label="编号" align="center" prop="id" v-if="false" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="设备归属水司" align="center" prop="tenantId" width="120" v-if="columns[1].visible" :show-overflow-tooltip="true"/> -->
          <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="用户编号" align="center" prop="userId" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="设备编号" align="center" prop="terminalId" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="IMEI" align="center" prop="imei" :show-overflow-tooltip="true" width="150"/>
          <!-- <el-table-column label="楼栋编号" align="center" prop="ldId" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="房间号" align="center" prop="roomId" v-if="false" :show-overflow-tooltip="true"/> -->
          <el-table-column label="厂家名称" align="center" prop="supplierId" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.supplierId"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="typeId" :show-overflow-tooltip="true" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.typeId"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="baseReading" :show-overflow-tooltip="true"/>
          <!-- (0：否，1：是) -->
          <el-table-column label="是否带阀控" align="center" prop="valveControl" width="120"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.valveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="通讯类型" align="center" prop="communicationType" v-if="columns[14].visible"
                           :show-overflow-tooltip="true" width="90">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.communication_type" :value="scope.row.communicationType"/>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="valveAddress" :show-overflow-tooltip="true"/>
          <el-table-column label="安装日期" align="center" prop="installDate" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="installAddress" :show-overflow-tooltip="true"/>
          <el-table-column label="抄表周期" align="center" prop="meterReaderCycle" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.reader_cycle" :value="scope.row.meterReaderCycle"/>
            </template>
          </el-table-column>
          <el-table-column label="表状态" align="center" prop="terminalMark" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.used_status" :value="scope.row.terminalMark"/>
            </template>
          </el-table-column>
          <el-table-column label="协议名称" align="center" prop="protocolName" :show-overflow-tooltip="true"
                           width="120"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" :show-overflow-tooltip="true"
                           width="180"/>
          <el-table-column label="集中器" align="center" prop="concentratorName" :show-overflow-tooltip="true"
                           width="100"/>
        </el-table>

        <pagination
          v-show="meteredtotal>0"
          :total="meteredtotal"
          :page.sync="meteredQueryParams.pageNum"
          :limit.sync="meteredQueryParams.pageSize"
          @pagination="getMeteredList"
          :page-sizes="[50, 100, 150]"
        />
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="MeteredCancel">取 消</el-button>
        <el-button type="primary" @click="submitMeteredForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleUpload" v-has-permi="['basedata:concentrator:exportTemplate']">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listMeterSheetsTree,} from "@/api/basedata/meterSheets";
import {deptList} from '@/api/system/dept.js'
import {getAreaTree} from "@/api/tree/index"
import {getCollectorByConcentratorId} from "@/api/record/collector";
import {
  bindTerminalsXb,
  listConcentrator,
  getConcentrator,
  delConcentrator,
  addConcentrator,
  updateConcentrator,
  concentratorOption,
  sendCommand,
  getFeedbackLog
} from "@/api/record/concentrator";
import {
  listTerminalxb,
} from "@/api/record/terminalxb";
import Treeselect from "@riophae/vue-treeselect";
import {protocolOption} from '@/api/record/protocol'
import "highlight.js/styles/github-gist.css";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";
import RegisterDialog from "@/views/record/metered/component/registerDialog.vue";


export default {
  name: 'ConcentratorController',
  dicts: ['communication_type','concentrator_command_type', 'terminal_supplier', 'frequency_meter_read', 'yes_no', 'module_type', 'reader_cycle', 'used_status', 'concentrator_supplier'],
  components: {
    Treeselect, RegisterDialog
  },
  data() {
    return {
      commandType: null,
      // 绑定户表操作Form表单参数
      bindTerminalsXbParams: {
        concentratorId: null,
        protocolId: null,
        terminalIds: null
      },
      sheetsCode: '',
      protocolId: '',
      userModalTitle: '户表选择',
      treeWidth: 0,
      queryResult: false,
      information: '',
      defaultExpandedKeys: [],
      // 客户下拉框中的数据
      deptOption: [],
      collectorList: {},
      commandName: '',
      tabPosition: 'left',
      feedbackContent: '',
      size: 'mini',
      uploadVisible: true,
      /* // 表单参数
       form: [],*/
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      labelWidth: '110px',
      // 是否显示弹出层-下发命令
      ControllerOpen: false,
      // 是否显示弹出层-户表
      meteredOpen: false,
      // 集中器下拉框
      concentratorOption: [],
      // 选中的户表
      selectMeteredMessage: '',
      selectMeteredList: [],
      // 日志表格数据
      logDataList: [],
      // 户表档案表格数据
      meteredDataList: [],
      // 日志记录加载状态
      logloading: false,
      // 户表表格加载状态
      meteredloading: false,
      // 日志记录总条数
      logtotal: 0,
      // 户表档案总条数
      meteredtotal: 0,
      // 时间
      sendTimeValue: [],
      selectedconcentratorNo: null,
      // 遮罩层
      loading: true,
      screenHeight: null,
      treeLoading: false,
      tableLoading: false,
      // 区域树选项
      sheetsTreeList: [],
      // 集中器管理表格数据
      concentratorList: [],
      // 协议下拉框
      protocolOptionList: [],
      terminalxbList: [],
      collapsiable: false,
      // 显示搜索条件
      showSearch: true,
      collapseAble: false,
      fold: false,
      maxShow: 4,
      // 列信息
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        sheetsCode: '',
        concentratorName: null,
        concentratorId: null,
        tenantId: null,
        terminalId: null,
        communicationType: null,
      },
      queryXbParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: '',
        concentratorId: '',
        terminalMark: 1,
        terminalId: null,
      },
      // 命令类型查询参数
      queryCommParams: {
        commandType: null,
      },
      // 日志记录查询参数
      logQueryParams: {
        pageNum: 1,
        pageSize: 20,
        // sheetsCode: null,
        commandType: null,
        concentratorId: null,
        params: {
          beginSendTime: null,
          endSendTime: null,
        }
      },
      // 户表查询页面参数
      meteredQueryParams: {
        pageNum: 1,
        pageSize: 50,
        terminalId: null,
        userId: null,
        imei: null,
        communicateAddress: null,
        TerminalMark: 1,
        concentratorId: null,
        haveConcentrator: null,
        concentratorAddress: null,
        communicationType: null,
        // sheetsCode: null,
        protocolId: null,
      },
      // 日志查询页面参数
      querylogParams: {
        pageNum: 1,
        pageSize: 20,

      },
// 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/concentrator/importData"
      },
      filterText: '',
      filterConcentrator: '',
      // 右侧横向tab默认选中
      activeName: '1',
      selectedConcentrator: {},
      selectedconcentratorId: null,
      // 表单
      form: {
        sheetsCode: null,
        concentratorId: '',
        supplierId: null,
        isOpen: '1',
        requestId: null,
        commandType: null,
        meter: null,
        meters: [],
        sendTime: null,
        frequency: null,
        ip: null,
        port: null,
        tenantId: null,
        terminalsXbs: [],
        collector: null,
        newConcentratorId: null,
        communicationType: null,
        frequencyUnit: 'DAYS',
        protocolId: null,
        enable: null,
      },
      controllerTitle: '命令下发',
      controllerForm:{
        isOpen: '1',
        sheetsCode: null,
        concentratorName: null,
        concentratorId: null,
        concentratorType: null,
        concentratorVer: null,
        protocolId: null,
        readDate: null,
        installAddress: null,
        communicationType: null,
        timeOver: null,
        ipAddress: null,
        port: null,
        netPoint: null,
        heartbeatCycle: null,
        simNum: null,
        ccid: null,
        lat: null,
        lng: null,
        lngLatTemp: null,
        remark: null,
        supplierId: null,
        tenantId: null,
        enable: true,
        frequencyUnit: null,
        terminalsXbs: null,
        meter: null,
      },
      controllerformrules: {
        supplierId: [
          {required: true, message: "集中器厂家不能为空", trigger: "change"}
        ],
        tenantId: [
          {required: true, message: "请选择所属客户", trigger: "change"}
        ],
        concentratorName: [
          {required: true, message: "集中器名称不能为空", trigger: "blur"}
        ],
      },
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "设备归属水司不能为空", trigger: "blur" }
        // ],
        sheetsCode: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        concentratorName: [
          {required: true, message: "集中器名称不能为空", trigger: "blur"}
        ],
        concentratorId: [
          {required: true, message: "集中器地址不能为空", trigger: "blur"}
        ],
        ProtocolType: [
          {required: true, message: "协议类型不能为空", trigger: "change"}
        ],
        heartbeatCycle: [
          {type: 'number', message: '必须为数字'}
        ],
        readDate: [
          {type: 'number', message: '必须为数字'}
        ],
        supplierId: [
          {required: true, message: "生产厂家不能为空", trigger: "change"}
        ],
        tenantId: [
          {required: true, message: "请选择所属客户", trigger: "change"}
        ],
        communicationType: [
          {required: true, message: "请选择通讯类型", trigger: "change"}
        ],
        // isOpen: [
        //   {required: true, message: "请选择阀控状态", trigger: "change"}
        // ]
      },
      // 列信息
      columns: [
        {key: 0, label: `自增主键`, visible: false},
        // { key: 1, label: `用户归属水司`, visible: false },
        {key: 0, label: `区域`, visible: true},
        {key: 1, label: `集中器名称`, visible: true},
        {key: 2, label: `集中器地址`, visible: true},
        {key: 3, label: `集中器型号`, visible: true},
        // { key: 4, label: `集中器版本`, visible: true },
        {key: 4, label: `协议类型`, visible: true},
        {key: 5, label: `抄表日期`, visible: true},
        {key: 6, label: `安装位置`, visible: true},
        // { key: 8, label: `通讯类型`, visible: true },
        // { key: 9, label: `超时时间`, visible: true },
        {key: 7, label: `IP地址`, visible: true},
        {key: 8, label: `端口`, visible: true},
        {key: 9, label: `心跳周期`, visible: true},
        {key: 10, label: `SIM卡号码`, visible: true},
        {key: 11, label: `终端位置纬度`, visible: true},
        {key: 12, label: `终端位置经度`, visible: true},
        {key: 13, label: `生产厂家`, visible: true},
        { key: 14, label: `通讯类型`, visible: true },
        // { key: 20, label: `备注`, visible: true },
      ],
    }
  },
  methods: {
    // 下载全部表档案
    loadAllReport() {
      let that = this
      that.$modal.confirm('是否下载全部表档案').then(function () {
        that.controllerForm.terminalsXbs = null
        // this.submitControllerForm()
        const loading = that.$loading({
          lock: true,
          text: '正在发送命令，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        return sendCommand(that.controllerForm).then(response => {
          that.queryResult = false
          loading.close();
          that.feedbackContent = response.data.msg
          if (response.data.data !== null && response.data.data !== undefined && response.data.data !== "") {
            that.queryResult = true
            that.information = response.data.data
          }
          that.$modal.msgSuccess("命令已下发！");
          that.ControllerOpen = false;
          that.getLogList();
          that.resetForm('form')
        })
      })
    },
    /**根据concentratorId获取采集器 */
    getConcentratorList() {
      getCollectorByConcentratorId(this.selectedConcentrator.id).then(response => {
        this.collectorList = response.rows
      })
    },
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: '' + node.sheetsCode,
        label: node.sheetsName,
        children: node.children
      };
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0) {
        this.treeLoading = false;
      } else {
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    /** 查询集中器管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.sheetsCode = this.$refs.tree.getCheckedKeys().join(',');
      listConcentrator(this.queryParams).then(response => {
        this.concentratorList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
      // this.handleTabClick(tab);
    },
    /** 查询绑定水表管理列表 */
    getXbList() {
      this.loading = true;
      // this.queryXbParams.ConcentratorId = this.selectedconcentratorId;
      if (Object.keys(this.selectedConcentrator).length === 0) {
        // this.queryXbParams.ConcentratorId = this.concentratorList[0].id;
        // this.selectedconcentratorId = this.concentratorList[0].id;
        return
      } else {
        this.queryXbParams.ConcentratorId = this.selectedConcentrator.id;
        this.queryXbParams.terminalId = this.queryParams.terminalId
        listTerminalxb(this.queryXbParams).then(response => {
          this.terminalxbList = response.rows;
          this.total = response.total
          this.loading = false;
        });
      }
    },
    // 点击区域树
    handleNodeClick(data) {
      this.selectedConcentrator = data
      // this.form.concentratorId = data.concentratorId
      // this.form.communicationType = data.communicationType
      this.sheetsCode = data.sheetsCode
      this.protocolId = data.protocolId
      // this.selectedconcentratorId = data.id
      // this.selectedconcentratorNo = data.concentratorId
      // this.bindTerminalsXbParams.protocolId = data.protocolId
      // this.bindTerminalsXbParams.concentratorId = data.id
      this.getConcentratorList()
      this.getXbList()
      this.getLogList()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加集中器管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row.id) {
        this.$message.error('请先选择集中器')
        return
      }
      this.reset();
      const id = row.id
      getConcentrator(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改集中器管理";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(Object.keys(this.selectedConcentrator).length === 0) {
        return this.$modal.msgError("请选择集中器");
      }
      const IDs = row.id || this.ids;
      this.$modal.confirm('是否确认删除集中器管理编号为"' + IDs + '"的数据项？').then(function () {
        return delConcentrator(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConcentrator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConcentrator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    //打开对话框
    openContorller() {
      this.selectMeteredList = []
      this.resetControllerForm()
      if (Object.keys(this.selectedConcentrator).length === 0) {
        this.$modal.msgWarning("请先选择集中器!")
        return
      }
      console.log(this.commandType,"this.commandType")
      if (this.commandType == null || this.commandType === '') {
        this.$modal.msgWarning("请选择命令!")
        return
      }else{
        this.controllerForm.commandType = this.commandType
      }
      this.controllerForm.commandType = this.commandType
      this.controllerForm.communicationType = this.selectedConcentrator.communicationType

      this.controllerForm.concentratorId = this.selectedConcentrator.concentratorId
      this.controllerForm.supplierId = this.selectedConcentrator.supplierId
      this.selectMeteredMessage = ''
      this.ControllerOpen = true;
      // if (this.title == '下发命令名称-配置绑定多个水表地址' || this.title === '下发命令名称-单表数据抄取' || this.title == '下发命令名称-阀控' || this.title == '下发命令名称-下载表档案'  || this.title === '下发命令名称-多表数据抄取' || this.title === '下载多表档案（QBT专用）') {
      //   this.getMeteredList()
      // }
      // if(this.controllerTitle === '下发命令名称-设置自动抄表上报时间及周期'){
      //   this.controllerForm.frequencyUnit = 'DAYS'
      // }
    },
    // 命令类型下拉框change
    change(e) {
      // 获取选中的集中器
      // let choseCheckList = this.concentratorList;
      // if (Object.keys(this.selectedConcentrator).length === 0) {
      //   this.$modal.msgWarning("请先选择集中器!")
      //   return
      // } else {
      //
      // }

      this.resetControllerForm()
      const type = this.dict.type.concentrator_command_type.filter((item) => item.label == e)
      // 命令
      this.commandType = type[0].value
      this.controllerTitle = '下发命令名称-' + type[0].label
      this.selectMeteredMessage = ''
    },

    // 获取集中器下拉框中的数据
    getConcentratorOption() {
      concentratorOption().then(response => {
        this.concentratorOption = response.rows
        this.concentratorOption.push({
          concentratorName: '全部',
          concentratorId: '',
        })
      })
    },
    // 获取协议下拉框数据
    getProtocolOption() {
      protocolOption().then(response => {
        this.protocolOptionList = response.data
      })
    },
    // 判断表的状态禁用表格多选按钮
    selectable(row, rowIndex) {
      if (row.terminalMark === 1) {
        return true;  //不禁用
      } else {
        return false;  //禁用
      }
    },
    // 点击选择户表按钮
    selectMetered(v) {
      this.userModalTitle = v
      this.resetForm("mQueryForm")
      this.controllerForm.meter = ''
      this.selectMeteredList = []
      if(this.$refs.meteredtable){
        this.$refs.meteredtable.clearSelection()
      }
      if(v==='户表选择'){
        // this.meteredQueryParams.sheetsCode = null
        this.meteredQueryParams.protocolId = null
        this.meteredQueryParams.haveConcentrator = true
        this.meteredQueryParams.concentratorAddress = this.controllerForm.concentratorId
        this.handleMeteredQuery()
      }else if(v==='绑定户表'){
        if (Object.keys(this.selectedConcentrator).length === 0) {
          return this.$modal.msgWarning("请先选择集中器!")
        }else{
          this.meteredQueryParams.protocolId = this.protocolId
          this.meteredQueryParams.concentratorAddress = null
          this.meteredQueryParams.haveConcentrator = false
          this.handleMeteredQuery()
        }
      }
      this.meteredOpen = true
    },
    // 户表档案多选框选中数据
    handleSelectionChange(selection) {
      if(this.userModalTitle === '户表选择'){
        if (this.controllerTitle === '下发命令名称-配置绑定多个水表地址' || this.controllerTitle === '下发命令名称-多表数据抄取' || this.controllerTitle === '下发命令名称-下载多表档案（QBT专用）') {
          this.selectMeteredList = selection
        } else if (this.controllerTitle === '下发命令名称-单表数据抄取' || this.controllerTitle === '下发命令名称-阀控' || this.controllerTitle === '下发命令名称-下载表档案' || this.controllerTitle == '下发命令名称-实时数据' || this.controllerTitle == '下发命令名称-日冻结数据') {
          if (selection.length > 1) {
            this.$refs.meteredtable.clearSelection()
            this.$refs.meteredtable.toggleRowSelection(selection.pop())
          }
          this.selectMeteredList = selection
        }
      }else if(this.userModalTitle === '绑定户表'){
        this.selectMeteredList = selection
      }
    },
    // getRowKeys(row) {
    //   return row.id
    // },

    // 获取日志记录数据
    getLogList() {
      this.logloading = true;
      if (this.sendTimeValue.length > 0) {
        this.logQueryParams.params.beginSendTime = this.sendTimeValue[0]
        this.logQueryParams.params.endSendTime = this.sendTimeValue[1]
      }
      this.logQueryParams.concentratorId = this.selectedConcentrator.concentratorId
      getFeedbackLog(this.logQueryParams).then(response => {
        this.logDataList = response.rows
        this.logtotal = response.total
        this.logloading = false;
      })
    },
    // 获取户表档案数据
    getMeteredList() {
      this.meteredloading = true;
      // this.meteredQueryParams.concentratorAddress = this.form.concentratorId
      listTerminalxb(this.meteredQueryParams).then(response => {
        this.meteredDataList = response.rows;
        this.meteredtotal = response.total;
        this.meteredloading = false;
      });
    },
    /** 日志记录查询搜索按钮操作 */
    handleLogQuery() {
      this.logQueryParams.pageNum = 1;
      this.getLogList();
    },
    /** 户表档案查询搜索按钮操作 */
    handleMeteredQuery() {
      this.meteredQueryParams.pageNum = 1;
      this.getMeteredList();
    },
    /** 日志记录查询搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置集中器查询操作 */
    resetQuery() {
      this.queryParams.concentratorId = null;
      this.queryParams.concentratorName = null;
      this.resetForm("queryForm")
      // this.queryParams.concentratorName = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetLogQuery() {
      this.sendTimeValue = []
      this.logQueryParams = {
        pageNum: 1,
        pageSize: 20,
        commandType: null,
        concentratorId: null,
        params: {
          beginSendTime: null,
          endSendTime: null,
        }
      }
      // this.resetForm("logQueryForm");
      this.handleLogQuery();
    },
    resetMeteredQuery() {
      this.resetForm("mQueryForm")
      this.handleMeteredQuery()
    },
    /** 下发命令 提交按钮 */
    submitControllerForm() {
      this.$refs["controllerform"].validate(valid => {
        if (valid) {
          if ((this.controllerTitle === '下发命令名称-配置绑定多个水表地址' || this.controllerTitle == '下发命令名称-单表数据抄取' || this.controllerTitle == '下发命令名称-阀控' || this.controllerTitle == '下发命令名称-实时数据' || this.controllerTitle == '下发命令名称-日冻结数据' || this.controllerTitle == '下发命令名称-多表数据抄取' || this.controllerTitle == '下发命令名称-下载多表档案（QBT专用）') && this.selectMeteredList.length == 0) {
            return this.$modal.msgWarning("请选择户表");
          }
          const loading = this.$loading({
            lock: true,
            text: '正在发送命令，请稍候...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (this.controllerTitle == '下发命令名称-批量读取缓存的最新抄表数据') {
            sendCommand(this.controllerForm).then(response => {
              loading.close();
              if (response.requestId) {
                getCommandResult({
                  requestId: response.requestId,
                  concentratorId: this.controllerForm.concentratorId
                }).then(response => {
                  this.queryResult = false
                  this.feedbackContent = response.data.msg
                  this.$modal.msgSuccess("命令已下发！");
                  this.ControllerOpen = false;
                  this.getLogList();
                  // this.getList()
                  this.resetControllerForm()
                  // this.$router.go(0);
                })
              } else {
                this.$modal.msgSuccess("命令已下发！");
                this.feedbackContent = response.data.msg
                this.ControllerOpen = false;
                this.getLogList();
                // this.getList()
                this.information = '';
                this.resetControllerForm()
                // this.$router.go(0);
              }
            })
          } else {
            sendCommand(this.controllerForm).then(response => {
              this.queryResult = false
              loading.close();
              this.feedbackContent = response.data.msg
              if (response.data.data !== null && response.data.data !== undefined && response.data.data !== "") {
                this.queryResult = true
                this.information = response.data.data
              }
              this.$modal.msgSuccess("命令已下发！");
              this.ControllerOpen = false;
              this.getLogList();
              // this.getList()
              this.resetControllerForm()
              // this.$router.go(0);
            })
          }
        }

      });

    },
    /** 户表档案 提交按钮 */
    submitMeteredForm() {
      var newSelection = ''
      this.controllerForm.terminalsXbs = null
      this.controllerForm.meter = null
      if (this.selectMeteredList.length > 0) {
        if(this.userModalTitle === '户表选择'){
          if (this.controllerTitle === '下发命令名称-配置绑定多个水表地址' || this.controllerTitle === '下发命令名称-下载多表档案（QBT专用）') {
            this.controllerForm.terminalsXbs = this.selectMeteredList
          } else if (this.controllerTitle === '下发命令名称-单表数据抄取' || this.controllerTitle === '下发命令名称-阀控' || this.controllerTitle === '下发命令名称-实时数据' || this.controllerTitle === '下发命令名称-日冻结数据' || this.controllerTitle === '下发命令名称-下载表档案') {
            this.controllerForm.meter = this.selectMeteredList[0].communicateAddress
          }else if(this.controllerTitle === '下发命令名称-多表数据抄取') {
            if(this.selectMeteredList.length > 5) {
              return this.$modal.msgWarning("最多选择五个")
            }else{
              this.controllerForm.meter = this.selectMeteredList.map(item => item.communicateAddress).join(", ")
            }
          }
          for (let i = 0; i < this.selectMeteredList.length; i++) {
            newSelection += this.selectMeteredList[i].terminalId + "、"
          }
          if (newSelection.length > 0) {
            newSelection = newSelection.substr(0, newSelection.length - 1);
          }
          this.selectMeteredMessage = '您选择了设备编号为：' + newSelection + '的表'
        }else if(this.userModalTitle === '绑定户表'){
          let temp = []
          this.selectMeteredList.map(item => {
            temp.push(item.id)
          })
          this.bindTerminalsXbParams.terminalIds = temp
          this.bindTerminalsXbParams.protocolId = this.selectedConcentrator.protocolId
          this.bindTerminalsXbParams.concentratorId = this.selectedConcentrator.id
          // 编写绑定户表的逻辑
          bindTerminalsXb(this.bindTerminalsXbParams).then(res =>{
            if(res.code === 200){
              this.getXbList()
              this.$modal.msgSuccess("绑定成功");
            }
          })
        }
      }
      this.meteredOpen = false
    },

    // 下发命令取消按钮
    ControllerCancel() {
      this.ControllerOpen = false;
      if (this.selectMeteredList.length > 0) {
        this.$refs.meteredtable.clearSelection()
      }
      this.selectMeteredList = []
    },
    // 户表档案取消按钮
    MeteredCancel() {
      this.meteredOpen = false;
      this.$refs.meteredtable.clearSelection()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 清空命令下发表单
    resetControllerForm() {
      this.controllerForm = {
        id: null,
        sheetsCode: null,
        concentratorName: null,
        concentratorId: null,
        concentratorType: null,
        concentratorVer: null,
        protocolId: null,
        readDate: null,
        installAddress: null,
        communicationType: null,
        timeOver: null,
        ipAddress: null,
        port: null,
        netPoint: null,
        heartbeatCycle: null,
        simNum: null,
        ccid: null,
        lat: null,
        lng: null,
        lngLatTemp: null,
        remark: null,
        supplierId: null,
        tenantId: null,
        enable: true,
        frequencyUnit: 'DAYS',
        isOpen: '1',
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sheetsCode: null,
        concentratorName: null,
        concentratorId: null,
        concentratorType: null,
        concentratorVer: null,
        protocolId: null,
        readDate: null,
        installAddress: null,
        communicationType: null,
        timeOver: null,
        ipAddress: null,
        port: null,
        netPoint: null,
        heartbeatCycle: null,
        simNum: null,
        ccid: null,
        lat: null,
        lng: null,
        lngLatTemp: null,
        remark: null,
        supplierId: null,
        tenantId: null,
        enable: null,
        frequencyUnit: null,
      };
      this.resetForm("form");
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    filterConcentratorNode(value, data) {
      if (!value) return true;
      return data.concentratorName.indexOf(value) !== -1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/concentrator/export', {
        ...this.queryParams
      }, `集中器_${new Date().getTime()}.xlsx`)
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 下载模板
    handleUpload() {
      this.download('basedata/concentrator/exportTemplate', {}, `集中器模板_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "集中器导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 切换单位 下发命令名称-设置自动抄表上报时间及周期
    handleUnitCommand(command){
      this.controllerForm.frequencyUnit = command
    },
  },
  created() {
    this.screenHeight = document.body.clientHeight
    this.getProtocolOption()
    this.getProtocolOption()
  },
  computed: {
    getAvailableHeight() {
      const height = (this.screenHeight - 220) + 'px'
      return {maxHeight: height, minHeight: height}
      // return this.screenHeight - (this.showSearch ? (this.fold ? 295 : 255) : 195)
    },
    getAvailableTableHeight() {
      // return this.screenHeight - 380
      return this.screenHeight - (this.showSearch ? (this.fold ? 440 : 420) : 380)
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterConcentrator(val) {
      this.$refs.concentratorTree.filter(val);
    },
    sendTimeValue(newVal) {
      if (newVal == null) {
        this.sendTimeValue = []
        this.logQueryParams.params = {
          beginSendTime: null,
          endSendTime: null
        }
      }
    }
  },
  mounted() {
    this.getTreeList()
    this.getList()
    this.getDeptList()
    this.treeWidth = this.$refs['tree']?.$el.offsetWidth - 15
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  }
}
</script>

<style scoped lang="scss">
.content-wrapper {
  margin-bottom: 16px;
}

.content-margin {
  margin-bottom: 16px;
}

.info-box {
  /* background-color: #F7FAFC; */
  width: 600px;
  height: 60px;
  padding: 10px 10px;
}

.el-tabs__item {
  width: 200px;
}

.clearfix:after {
  content: ' ';
  display: block;
  height: 0;
  clear: both;
}

.left {
  float: left;
}

.right {
  float: right;
}


.title {
  font-size: 18px;
  font-weight: bold;
  text-align: right;
  width: 200px;
}


::v-deep .el-descriptions-item__cell.el-descriptions-item__label.is-bordered-label {
  width: 110px;
  text-align: right;
  padding: 8px;
}

::v-deep .el-descriptions-item__cell.el-descriptions-item__content {
  min-width: 150px;
  padding: 8px;
}

// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
    //min-width: var(--treeWidth);
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 23%;
  }
}
.form_query {
  width: 20%;
  text-align: right;
}
</style>
